

package ws_sax;

import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class SAXContentProcessing extends DefaultHandler {

    static String user = null;
    static boolean found = false;
    static boolean IDfound = false;
    static boolean namefound = false;
    
    public static void main(String[] args) {
        if (args.length != 0) {
            System.out.println("Usage: java SAXContentProcessing StudentList.xml");
            System.exit(1);
        }
        SAXContentProcessing saxObject = new SAXContentProcessing();
        SAXParserFactory spf = SAXParserFactory.newInstance();

        try {
            SAXParser parser = spf.newSAXParser();
            parser.parse(new File("StudentList.xml"), saxObject);
            //parser.parse(new File(args[0]), saxObject);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
        
    }
    //

    public void characters(char[] buf, int off, int len)
            throws SAXException{
        String str = new String(buf, off, len);
        str = str.trim();
        //print id
        if (IDfound) {
            System.out.println("ID: " + str);
            IDfound = false;
        }
        //print name
        if (namefound) {
            System.out.println("Name: "+ str + "\n");
            namefound = false;
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equals("ID")) {
            IDfound = true;
        }
        if (qName.equals("name")) {
            namefound = true;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.println("Ket thuc " + uri);
    }

    

}
